package com.oneCommerce.controllers;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@ManagedBean
@RequestScoped
public class PhotoStreamer {
  
    private static StreamedContent defaultFileContent;
    private StreamedContent fileContent;
    @EJB
    private com.oneCommerce.beans.PhotosFacade ejbFacade;

    public StreamedContent getFileContent() throws FileNotFoundException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        String photoId = externalContext.getRequestParameterMap().get("photo_id");
        if (photoId == null || photoId.equals("")) {
            fileContent = defaultFileContent;
        } else {
            int parsedId = Integer.parseInt(photoId);
            if (parsedId < 0) {
                fileContent = defaultFileContent;
            }                                    
            String photoPath = ejbFacade.findByIdPhoto(new BigDecimal(photoId)).getPhotopath().replaceAll("/", "\\");            
            StreamedContent content = new DefaultStreamedContent(new FileInputStream(photoPath), "image/jpeg");
            return content;            
        }
        return fileContent;
    }

    public void setFileContent(StreamedContent fileContent) {
        this.fileContent = fileContent;
    }

    static {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = contextClassLoader.getResourceAsStream("resources/images/Photo - 0.png");
        defaultFileContent = new DefaultStreamedContent(inputStream, "image/png");
    }
}
